# -*- coding:utf-8 -*-
from __future__ import division
from wordcloud import WordCloud,ImageColorGenerator
from dao.MySqlDAL import MySqlDAL
import matplotlib.pyplot as plt
import util.word_seg_util as wordutil
from PIL import Image
import numpy as np
import os
from config.dbconf import basePath
import random

__author__ = 'shudongma.msd(风骐)'


sqlUtil = MySqlDAL()

res = sqlUtil.get_dimensions_rows('select id,title,content,keywords,type,date from tb_stock_news where date >= "2016-03-01" and date <= "2016-03-31"')
content = ''
for row in res:
    content += row['content']

words = wordutil.extract_tags_standard(content,topK=1000,withWeight=True)

drawwords = []
for row in words:
    if row[0] in  wordutil.moodwords:
        drawwords.append(row)

# 效果一 : 普通无蒙版
# wordcloud = WordCloud()
# wordcloud.fit_words(drawwords)
#
# # draw
# plt.imshow(wordcloud)
# plt.axis("off")
# plt.show()

# 效果二 ：利用胡歌头像
# word_mask = np.array(Image.open(os.path.join(basePath, "resources/huge.jpg")))
# wordcloud = WordCloud(background_color='white',mask=word_mask)
# wordcloud.fit_words(drawwords)
#
# wordcloud.to_file("wordcloud.png")
#
# # draw
# plt.imshow(wordcloud)
# plt.axis("off")
# plt.show()
#
# plt.imshow(wordcloud)
# plt.axis("off")
# # plt.figure()
# # plt.imshow(word_mask, cmap=plt.cm.gray)
# # plt.axis("off")
# plt.show()


# 效果三 :色彩增效
def grey_color_func(word, font_size, position, orientation, random_state=None, **kwargs):
    return "hsl(0, 0%%, %d%%)" % random.randint(60, 100)

word_mask = np.array(Image.open(os.path.join(basePath, "resources/batman.jpg")))
wordcloud = WordCloud(mask=word_mask,margin=10,random_state=1)
wordcloud.fit_words(drawwords)
default_colors = wordcloud.to_array()

plt.title("Custom colors")
plt.imshow(wordcloud.recolor(color_func=grey_color_func, random_state=3))
# wordcloud.to_file("batman.png")
plt.axis("off")
plt.figure()
plt.title("Default colors")
plt.imshow(default_colors)
plt.axis("off")
plt.show()


# 效果四：多彩
# word_mask = np.array(Image.open(os.path.join(basePath, "resources/batman.jpg")))
# wordcloud = WordCloud(background_color="white",mask=word_mask,margin=10)
# wordcloud.fit_words(drawwords)
# # create coloring from image
# image_colors = ImageColorGenerator(word_mask)
#
# # show
# plt.imshow(wordcloud)
# plt.axis("off")
# plt.figure()
# # recolor wordcloud and show
# # we could also give color_func=image_colors directly in the constructor
# plt.imshow(wordcloud.recolor(color_func=image_colors))
# plt.axis("off")
# plt.figure()
# plt.imshow(wordcloud, cmap=plt.cm.gray)
# plt.axis("off")
# plt.show()


# # 打印出内容粘贴到https://tagul.com网站生成
# for row in drawwords:
#     for i in xrange(int(row[1]*1000)):
#         print row[0]